<?php

namespace app\admin\model;

use app\api\model\Url;
use fast\Http;
use think\Log;
use think\Model;
use think\Request;


Class Joinpay extends Model {

    // 交易成功回调地址，如不接收回调不必提供
    private $callback_url = "";
    private $key = "";
    private $merchant_report_no = "888121600007762";

    private $domain;

    const SINGLEPAY_URL = 'https://www.joinpay.com/payment/pay/singlePay';

    const SINGLEPAY_QUERY_URL = 'https://www.joinpay.com/payment/pay/singlePayQuery';


    public function __construct($merchant_id = '', $key = '') {
        $this->domain  = Request::instance()->domain();
        $this->key = 'baa07d27b77544f282d1f77fca935553';


    }

    /**
     * 生成签名
     * @param $params
     * @param $key
     * @param string $encryptType
     * @return string
     */
    public function hmacRequest($params, $key, $encryptType = "1")
    {
        if ("1" == $encryptType) {
            return md5(implode("", $params) . $key);
        } else {
            $private_key = openssl_pkey_get_private($key);
            $params = implode("", $params);
            openssl_sign($params, $sign, $private_key, OPENSSL_ALGO_MD5);
            openssl_free_key($private_key);
            $sign = base64_encode($sign);
            return $sign;
        }
    }

    /**
     * @param $param
     * @return string[] 批量代付
     */
    public function batchPay($reveice){
        global $_W;

        //商户信息
        $data = [];
        $data['userNo']                         =  $this->merchant_report_no;
        $data['productCode']                    =  'BANK_PAY_DAILY_ORDER';
        $data['requestTime']                    =  date('Y-m-d H:i:s', $reveice['createtime']);
        $data['merchantOrderNo']                =  $reveice["ordersn"];
        $data['receiverAccountNoEnc']           =  $reveice["bankcard"];
        $data['receiverNameEnc']                =  $reveice["realname"];
        $data['receiverAccountType']            =  '201';
        $data['receiverBankChannelNo']          =  '';
        $data['paidAmount']                     =  $reveice["realmoney"];
        $data['currency']                       =  '201';
        $data['isChecked']                      =  '201';
        $data['paidDesc']                       =  '资金下发';
        $data['paidUse']                        =  '207';
        $data['callbackUrl']                    =  request()->domain().'/addons/thirdpay/Joinpay_batchpay_notify';

        if ($reveice['ispublic'] == 1){
            $data['receiverAccountType']        =  '204';
            $data['receiverBankChannelNo']      =  $reveice['bankopen'];
        }

        // 验签方式
        $pm_encryptType = 1;
        // 根据验签方式提交 MD5
        if ($pm_encryptType == "1") {
            // 获取到页面提交的MD5 KEY
            $hmacVal = urlencode($this->hmacRequest($data,$this->key));
            $data['hmac'] = $hmacVal;
        }

        //保存生成的验签
        $ret =  $this->post_json(self::SINGLEPAY_URL, json_encode($data));

        return json_decode($ret, true);
    }

    /**
     * @param $param
     * 批量代付查询
     */
    public function batchPayQuery($param){
        global $_W;

        //商户信息
        $merchants = [];
        $merchants['userNo']            =  $param['userNo'];
        $merchants['merchantBatchNo']       =  $param['productCode'];

        // 验签方式
        $pm_encryptType = 1;
        // 根据验签方式提交 MD5
        if ($pm_encryptType == "1") {
            // 获取到页面提交的MD5 KEY
            $hmacVal = urlencode($this->hmacRequest($merchants,$param["keymd5"]));
            $merchants['hmac'] = $hmacVal;
        }

        //保存生成的验签
        pdo_insert('ewei_shop_payinfo', array('sign'=>'', 'ordersn'=>$param["tid"], 'status'=>1, 'createtime'=>time()));

        return array('url' => Url::BATCH_PAY_QUERY_URL . '?' . http_build_query($merchants, '', '&'));
    }

    /**
     * 可用余额查询
     */
    public function accountBalanceQuery($param){

        //商户信息
        $data = [];
        $data['userNo'] = $this->merchant_report_no;

        // 验签方式
        $pm_encryptType = 1;
        // 根据验签方式提交 MD5
        if ($pm_encryptType == "1") {
            // 获取到页面提交的MD5 KEY
            $hmacVal = urlencode($this->hmacRequest($data,$this->key));
            $data['hmac'] = $hmacVal;
        }

        $ret =  $this->post_json(Url::ACCOUNT_BALANCE_QUERY_URL, json_encode($data));


        return json_decode($ret, true);
        /*        return array('url' => Url::ACCOUNT_BALANCE_QUERY_URL . '?' . http_build_query($data, '', '&'));*/
    }

    /**
     * @param $param
     * @return string[] 订单退款
     */
    public function orderRedund($param){
        global $_W;

        //商户信息
        $data = [];
        $data['p1_MerchantNo']              =  $this->merchant_report_no;
        $data['p2_OrderNo']                 =  $param['productCode'];
        $data['p3_RefundOrderNo']           =  $param['p3_RefundOrderNo'];
        $data['p4_RefundAmount']            =  floatval($param['p4_RefundAmount']);
        $data['p5_RefundReason']            =  $param['p5_RefundReason'];
        $data['p6_NotifyUrl']               =  'https://baidu.com';
//        $data['q1_version']                 =  '2.2';

        // 验签方式
        $pm_encryptType = 1;
        // 根据验签方式提交 MD5
        if ($pm_encryptType == "1") {
            // 获取到页面提交的MD5 KEY
            $hmacVal = urlencode($this->hmacRequest($data,$param['verifycode']));
            $data['hmac'] = $hmacVal;
        }

        //保存生成的验签
//        pdo_insert('ewei_shop_payinfo', array('sign'=>'', 'ordersn'=>$param["tid"], 'status'=>1, 'createtime'=>time()));

        $ret =  $this->http_post(self::REFUND_URL , ($data));
        $ret = json_decode($ret,true);

        $ret['message'] = $ret['rc_CodeMsg'];

        return $ret['rb_Code']==100?true:false;
    }

    function http_post($url, $params,$contentType=false)
    {

        if (function_exists('curl_init')) { // curl方式
            $oCurl = curl_init();
            if (stripos($url, 'https://') !== FALSE) {
                curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            }
            $string = $params;
            if (is_array($params)) {
                $aPOST = array();
                foreach ($params as $key => $val) {
                    $aPOST[] = $key . '=' . urlencode($val);
                }
                $string = join('&', $aPOST);
            }
            curl_setopt($oCurl, CURLOPT_URL, $url);
            curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($oCurl, CURLOPT_POST, TRUE);
            //$contentType json处理
            if($contentType){
                $headers = array(
                    "Content-type: application/json;charset='utf-8'",
                );

                curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($oCurl, CURLOPT_POSTFIELDS, json_encode($params));
            }else{
                curl_setopt($oCurl, CURLOPT_POSTFIELDS, $string);
            }
            $response = curl_exec($oCurl);
            curl_close($oCurl);
            return $response;
//        return json_decode($response, true);
        } elseif (function_exists('stream_context_create')) { // php5.3以上
            $opts = array(
                'http' => array(
                    'method' => 'POST',
                    'header' => 'Content-type: application/x-www-form-urlencoded',
                    'content' => http_build_query($params),
                )
            );
            $_opts = stream_context_get_params(stream_context_get_default());
            $context = stream_context_create(array_merge_recursive($_opts['options'], $opts));
            return file_get_contents($url, false, $context);
//        return json_decode(file_get_contents($url, false, $context), true);
        } else {
            return FALSE;
        }
    }

    public function orderQuery($param){
        global $_W;

        //商户信息
        $data = [];
        $data['p0_Version']                 =  '2.3';
        $data['p1_MerchantNo']              =  $this->merchant_report_no;
        $data['p2_OrderNo']                 =  $param['ordersn'];

        // 验签方式
        $pm_encryptType = 1;
        // 根据验签方式提交 MD5
        if ($pm_encryptType == "1") {
            // 获取到页面提交的MD5 KEY
            $hmacVal = urlencode($this->hmacRequest($data,$this->key));
            $data['hmac'] = $hmacVal;
        }

        //保存生成的验签
//        pdo_insert('ewei_shop_payinfo', array('sign'=>'', 'ordersn'=>$param["tid"], 'status'=>1, 'createtime'=>time()));
        $ret =  $this->http_post(Url::ORDERQUERY_URL , $data);
        $ret = json_decode($ret,true);var_dump($ret['r6_BankTrxNo']);
        return $ret['r6_BankTrxNo'];
//        return array('url' => Url::BATCH_PAY_QUERY_URL . '?' . http_build_query($data, '', '&'));
    }

    public function netpay($param){
        global $_W;

        //商户信息
        $data = [];
        $data['method']                     =  'netPay.prePay';
        $data['version']                    =  '1.0';
        $data['rand_str']                   =  $this->nonce_str();
        $data['sign_type']                  =  '2';
        $data['mch_no']                     =  $param["mch_no"];

        // 验签方式
        $pm_encryptType = 1;
        // 根据验签方式提交 MD5
        if ($pm_encryptType == "1") {
            // 获取到页面提交的MD5 KEY
            $hmacVal = urlencode($this->hmacRequest($data,$param["keymd5"]));
            $data['hmac'] = $hmacVal;
        }

        //保存生成的验签
        pdo_insert('ewei_shop_payinfo', array('sign'=>'', 'ordersn'=>$param["tid"], 'status'=>1, 'createtime'=>time()));

        return array('url' => Url::NET_PAY_URL . '?' . http_build_query($data, '', '&'));
    }

    private function nonce_str() {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $length = strlen($characters);
        $nonce_str = '';
        for ($i = 0; $i < 32; $i++) {
            $nonce_str .= $characters[rand(0, $length - 1)];
        }
        return $nonce_str;
    }

    public function singlePay($param, $reveice){
        global $_W;

        //商户信息
        $data = [];
        $data['userNo']                         =  $this->merchant_report_no;
        $data['productCode']                    =  'BANK_PAY_DAILY_ORDER';
        $data['requestTime']                    =  date('Y-m-d H:i:s', $reveice['createtime']);
        $data['merchantOrderNo']                =  $reveice["logno"];
        $data['receiverAccountNoEnc']           =  $reveice["bankcard"];
        $data['receiverNameEnc']                =  $reveice["realname"];
        $data['receiverAccountType']            =  '201';
        $data['receiverBankChannelNo']          =  '';
        $data['paidAmount']                     =  $reveice["realmoney"];
        $data['currency']                       =  '201';
        $data['isChecked']                      =  '201';
        $data['paidDesc']                       =  $reveice["remark"];
        $data['paidUse']                        =  '207';
        $data['callbackUrl']                    = $_W['siteroot'].'addons/ewei_shopv2/payment/joinpay/callback.php';

        if ($reveice['ispublic'] == 1){
            $data['receiverAccountType']                =  '204';
            $data['receiverBankChannelNo']              =  $reveice['bankopen'];
        }

        // 验签方式
        $pm_encryptType = 1;
        // 根据验签方式提交 MD5
        if ($pm_encryptType == "1") {
            // 获取到页面提交的MD5 KEY
            $hmacVal = urlencode($this->hmacRequest($data,$this->key));
            $data['hmac'] = $hmacVal;
        }


        //保存生成的验签
        $ret =  $this->post_json(Url::SINGLEPAY_URL, json_encode($data));
        return json_decode($ret, true);

//        return array('url' => Url::SINGLEPAY_URL . '?' . http_build_query($data, '', '&'));
    }

    public function post_json($url, $data){
        $ch = curl_init($url);
        $header = array();
        $header[] = 'content-type: application/json';

        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_HEADER, 0);//设定是否输出页面内容
        curl_setopt($ch,CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1); // post,get 过去
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不验证证书
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1 );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,10);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        //curl_setopt($ch, CURLOPT_PROXY, '192.168.0.12'); //代理服务器地址
        //curl_setopt($ch, CURLOPT_PROXYPORT, 8888); //代理服务器端口
//        echo('post ' . $url . '?' . $data);
        $filecontent = curl_exec($ch);
//        echo($filecontent);
        return $filecontent;
    }

    public function singlePayQuery($param){
        global $_W;

        //商户信息
        $data = [];
        $data['userNo']                         = $this->merchant_report_no;
        $data['merchantOrderNo']                =  $param["merchantOrderNo"];

        // 验签方式
        $pm_encryptType = 1;
        // 根据验签方式提交 MD5
        if ($pm_encryptType == "1") {
            // 获取到页面提交的MD5 KEY
            $hmacVal = urlencode($this->hmacRequest($data,$this->key));
            $data['hmac'] = $hmacVal;
        }

        $ret =  $this->post_json(self::SINGLEPAY_QUERY_URL, json_encode($data));
        return json_decode($ret, true);
    }

    public function join_singlePayQuery($id){
        global $_W,$_GPC;

        $log = pdo_fetch('select * from ' . tablename('ewei_shop_member_log') . ' where id=:id ', array(':id' => $id));

        $sec = m('common')->getSec();
        $sec = iunserializer($sec['sec']);
        $join_pay = trim($sec['join_pay']['open'])?1:0;
        if ($join_pay == 0){
            return false;
//            show_json(0, '聚合代付未开启');
        }

//        $merch_payment = pdo_fetch('select * from ' . tablename('ewei_shop_merch_user_payment'). ' where merchid=:merchid and status=1 ', array(':merchid' => $log['merchid']));
        $merch_payment['merchantOrderNo'] = $log['logno'];

        $ret = m('joinpay')->singlePayQuery($merch_payment);

        //205 订单完成
        if ($ret['data']['status'] == '205'){
            pdo_update('ewei_shop_member_log', array('status'=>1,'errorcode' => '111111'), array('id' => $id));
            return false;
        }else{
            //214 不存在就是没有下单
            if ($ret['data']['status'] == '214'){
                return true;
            }else{
                if ($ret['data']['status'] != '201' && $ret['data']['status'] != '202' && $ret['data']['status'] != '203' && $ret['data']['status'] != '205'){
                    //更新状态
                    if ($ret['data']['status'] == '208'){
                        $ret['data']['errorCode'] = '208';
                        $ret['data']['errorDesc'] = '已拒绝';
                    }
                    pdo_update('ewei_shop_member_log', array('status'=>-1,'errorcode' => $ret['data']['errorCode'], 'errormsg' =>  $ret['data']['errorDesc']), array('id' => $id));
                    if ($log['money'] > 0) {
                        //申请的钱打回余额
                        m('member')->setCredit($log['openid'], 'credit2j', $log['money'], array(0, '余额提现退回'));
                    }

                    return false;
                }
            }
        }



        return true;
    }

    public function orderClose($param)
    {
        global $_W;

        //商户信息
        $data = [];
        $data['p1_MerchantNo'] = $this->merchant_report_no;
        $data['p2_OrderNo'] = $param['ordersn'];
        $data['p3_FrpCode'] = $param['frpcode'];

        // 验签方式
        $pm_encryptType = 1;
        // 根据验签方式提交 MD5
        if ($pm_encryptType == "1") {
            // 获取到页面提交的MD5 KEY
            $hmacVal = urlencode($this->hmacRequest($data, $this->key));
            $data['hmac'] = $hmacVal;
        }

        $url = 'https://www.joinpay.com/trade/closeOrder.action';
        $ret = $this->http_post($url, ($data));

        $ret = json_decode($ret, true);;
        $ret['message'] = $ret['rc_CodeMsg'];

        if ($ret['rb_Code'] == 100 && $ret['ra_Status'] == '100'){
            return true;
        }

        return false;
    }



}

